package edu.colorado.karl.login;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * This class provides miscellaneous functions used in the login package.
 * @author Addison LeMessurier
 * @version 3/2/08
 */
public abstract class LoginUtil {
	private LoginUtil() {
		//	Class is abstract, can't instantiate
	}
	
	/**
	 * This function takes a string and returns its MD5 hash as a string
	 * @param text Text to hash.
	 * @return a MD5 hash of the given text.
	 */ 
	public static String MD5(String text) {
		MessageDigest digest = null;
		byte[] hash = new byte[32];

		try {
			digest = MessageDigest.getInstance("MD5");
		}

		catch (NoSuchAlgorithmException e) {
			// fail!
			System.out.println(e);
		}

		try {
			digest.update(text.getBytes("iso-8859-1"), 0, text.length());
			hash = digest.digest();
		}

		catch (UnsupportedEncodingException e) {
			// fail!
			System.out.println(e);
		}

		return convertToHex(hash);
	}
	
	private static String convertToHex(byte[] data) {
		StringBuffer buffer = new StringBuffer();
		int i, halfByte, twoHalves;

		for (i = 0; i < data.length; i++) {
			halfByte = (data[i] >>> 4) & 0x0F;
			twoHalves = 0;
			do {
				if ((0 <= halfByte) && (halfByte <= 9)) {
					buffer.append((char) ('0' + halfByte));
				}

				else {
					buffer.append((char) ('a' + (halfByte - 10)));
					halfByte = data[i] & 0x0F;
				}
			} while (twoHalves++ < 1);
		}
		return buffer.toString();
	}
}
